import React, { useState, useRef, useContext, useEffect, useMemo, useCallback, memo } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import styles from './index.less';

export type PreProps = {
  name?: string;
  show?: Boolean;
};

const MyContext = React.createContext({});

const usePrevious = (state: any) => {
  const ref = useRef();

  useEffect(() => {
    ref.current = state;
  }, [state]);
  return ref.current;
};

const ChildComp = memo((props: any) => {
  console.log('render child-comp ...');
  return (
    <div>
      <p>{props.age}</p>
      <button onClick={() => props.onClick('hello')}>改变 name 值</button>
    </div>
  );
});

const Pre: React.FC = () => {
  const value: PreProps = useContext(MyContext);
  return <div>{value.show ? <p>{value.name}</p> : '隐藏'}</div>;
};

const test: React.FC = () => {
  const [name, setName] = useState<string>('测试');
  const [show, setShow] = useState<Boolean>(false);
  const [count, setCount] = useState<number>(0);
  const prevCount = usePrevious(count);
  const dobuleCount = useMemo(() => {
    return count * 2;
  }, [count]);

  const handleChange = () => {
    setCount(count + 1);

    setName('显示');
    // setShow(!show);
  };

  const [age, setAge] = useState(0);
  const change = useCallback(() => {
    setAge(Math.random());
  }, []);

  return (
    <PageContainer>
      <p className={styles.test} onClick={() => handleChange()}>
        测试{prevCount} {count} {dobuleCount}
      </p>
      <MyContext.Provider value={{ name: name, show: show }}>
        <Pre></Pre>
      </MyContext.Provider>
      <ChildComp age={age} onClick={change} />
    </PageContainer>
  );
};
export default test;
